package com.yxsk.relay.job.component.common.net.serialization;

import com.alibaba.fastjson.JSONObject;
import com.yxsk.relay.job.component.common.exception.serialization.MessageSerializeException;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Description
 * @Author 11376
 * @CreateTime 2019/9/9 9:53
 */
public class JsonMessageEntitySerializer implements MessageEntitySerializer {

    private static final Charset CODE_CHARSET = StandardCharsets.UTF_8;

    @Override
    public <T> T deserialize(byte[] message, Class<T> type) throws MessageSerializeException {
        try {
            if (message != null) {
                String json = new String(message, CODE_CHARSET);
                return JSONObject.parseObject(json, type);
            }
        } catch (Exception e) {
            throw new MessageSerializeException(e);
        }
        return null;
    }

    @Override
    public byte[] serialize(Object o) throws MessageSerializeException {
        if (o != null) {
            try {
                String json = JSONObject.toJSONString(o);
                return json.getBytes(CODE_CHARSET);
            } catch (Exception e) {
                throw new MessageSerializeException(e);
            }
        }
        return null;
    }

}
